import { createRef, useImperativeHandle, forwardRef, useState, Ref } from 'react'
import * as ReactDOM from 'react-dom/client'
import './style.less'

type LoadingBarRefType = {
  setProgress(value: number): void
}

/* 进度组件 */
const LoadingBarComponent = forwardRef((props: any, ref: Ref<LoadingBarRefType>) => {
  const [progress, setProgress] = useState(0)

  useImperativeHandle(ref, () => ({
    setProgress: (value: number) => setProgress(value)
  }))

  return (
    <div className="loading-bar-content" style={{ width: `${progress}%` }}></div>
  )
})

/* 进度服务 */
class LoadingBar {
  // 根实例
  root: ReactDOM.Root | null = null
  // 进度组件ref
  loadingBarRef = createRef<LoadingBarRefType>()

  constructor () {
    let rootDom = document.querySelector('#loading-bar-container')
    if (!rootDom) {
      rootDom = document.createElement('div')
      rootDom.id = 'loading-bar-container'
    }
    rootDom.className = 'loading-bar-container'
    document.body.appendChild(rootDom)
    this.root = ReactDOM.createRoot(rootDom)
    this.root.render(<LoadingBarComponent ref={this.loadingBarRef} />)
  }
  // 卸载
  unmount () {
    this.root?.unmount()
  }

  /* 单例模式 */
  static instance: LoadingBar | null = null

  static start (progress = 90) {
    if (this.instance) {
      return
    }
    this.instance = new LoadingBar()
    setTimeout(() => {
      this.update(progress)
    })
  }

  static update (progress: number) {
    if (progress > 100 || progress < 0) {
      return
    }
    this.instance?.loadingBarRef.current?.setProgress(progress)
  }

  static stop () {
    this.update(100)
    setTimeout(() => {
      this.instance?.unmount()
    }, 1000)
  }
}
export const useLoadingBar = () => LoadingBar
export default LoadingBar
